package juc.scenarios.startup;

import juc.scenarios.startup.model.ServiceStatus;
import juc.scenarios.startup.model.ServiceCheckResult;
import juc.scenarios.startup.service.impl.*;

import java.util.Arrays;
import java.util.List;

/**
 * 完整的服务启动检查演示
 * <p>
 * 演示使用CountDownLatch协调多个服务并发检查
 */
public class StartupCheckDemo {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== 完整服务启动检查演示 ===");

        // 创建服务检查列表
        List<juc.scenarios.startup.service.HealthCheckService> services = Arrays.asList(
                new DatabaseHealthCheckService(),
                new CacheHealthCheckService(),
                new MessageQueueHealthCheckService(),
                new ConfigCenterHealthCheckService()
        );

        // 创建检查管理器（手动设置服务列表）
        StartupCheckManager checkManager = new StartupCheckManager();
        // 由于Spring的依赖注入，我们需要手动设置服务列表
        // 在实际应用中，这些服务会通过@Autowired自动注入
        checkManager.healthCheckServices = services;

        System.out.println("开始执行服务启动检查...");
        System.out.println("检查的服务数量: " + services.size());
        System.out.println("服务列表: " + services.stream()
                .map(juc.scenarios.startup.service.HealthCheckService::getServiceName)
                .toList());

        long startTime = System.currentTimeMillis();

        try {
            // 执行检查（15秒超时）
            ServiceCheckResult result = checkManager.performStartupChecks(15000L);

            long endTime = System.currentTimeMillis();
            long totalDuration = endTime - startTime;

            // 输出结果
            System.out.println("\n=== 检查结果 ===");
            System.out.println("检查ID: " + result.getCheckId());
            System.out.println("总耗时: " + result.getTotalDuration() + "ms");
            System.out.println("API总耗时: " + totalDuration + "ms");
            System.out.println("总服务数: " + result.getTotalServices());
            System.out.println("健康服务数: " + result.getHealthyServices());
            System.out.println("异常服务数: " + result.getUnhealthyServices());
            System.out.println("是否全部健康: " + (result.isAllHealthy() ? "是" : "否"));

            System.out.println("\n=== 详细状态 ===");
            result.getServiceStatusMap().forEach((serviceName, status) -> {
                System.out.println("服务: " + serviceName);
                System.out.println("  状态: " + getStatusEmoji(status.getState()) + " " + status.getState());
                System.out.println("  耗时: " + status.getDuration() + "ms");
                System.out.println("  消息: " + status.getMessage());
                System.out.println();
            });

            // 性能分析
            if (result.isAllHealthy()) {
                System.out.println("🎉 所有服务检查通过，系统可以正常启动！");
            } else {
                System.out.println("⚠️  有服务异常，系统启动失败！");
            }

            // 性能对比
            System.out.println("\n=== 性能分析 ===");
            long estimatedSerialTime = result.getServiceStatusMap().values().stream()
                    .mapToLong(ServiceStatus::getDuration)
                    .sum();
            System.out.println("串行检查预估时间: " + estimatedSerialTime + "ms");
            System.out.println("并行检查实际时间: " + result.getTotalDuration() + "ms");
            System.out.println("节省时间: " + (estimatedSerialTime - result.getTotalDuration()) + "ms");
            System.out.println("效率提升: " + String.format("%.1f%%",
                    (double) (estimatedSerialTime - result.getTotalDuration()) / estimatedSerialTime * 100));

        } catch (Exception e) {
            System.err.println("检查过程中发生异常: " + e.getMessage());
            e.printStackTrace();
        }

        System.out.println("\n=== 演示完成 ===");

        // CountDownLatch 学习要点
        System.out.println("\n📚 本次演示中CountDownLatch的作用：");
        System.out.println("1. 🎯 协调多个服务并发检查");
        System.out.println("2. ⏱️  等待所有检查完成后统一汇总结果");
        System.out.println("3. 🔒 确保结果收集的线程安全性");
        System.out.println("4. ⚡ 大幅提升检查效率（并行 vs 串行）");
        System.out.println("5. 🛡️ 支持超时机制，避免永久等待");
    }

    private static String getStatusEmoji(ServiceStatus.ServiceState state) {
        if (state == ServiceStatus.ServiceState.HEALTHY) {
            return "✅";
        } else if (state == ServiceStatus.ServiceState.UNHEALTHY) {
            return "❌";
        } else if (state == ServiceStatus.ServiceState.TIMEOUT) {
            return "⏰";
        } else if (state == ServiceStatus.ServiceState.PENDING) {
            return "⏳";
        } else if (state == ServiceStatus.ServiceState.CHECKING) {
            return "🔍";
        } else {
            return "❓";
        }
    }
}